var multiparty = require('multiparty');//大文件上传中间件
var moment = require('moment');//时间格式化中间件
var filepath = require('../conf/config')['filepath'];

exports.fileupload = function (req,res,next) {
    //生成multiparty对象，并配置上传目标路径
    var form = new multiparty.Form({uploadDir: filepath});
    //上传完成后处理
    form.parse(req, function (err, fields, files) {
        if (err) {
            console.log('parse error: ' + err);
            var result = {};
            result.code = "-999";
            result.msg = "上传失败:"+err;
            res.status(200).send(result);
        } else {
            //注意imageData仍为文件数组类型
            var imageFile = (files.imageData)[0];
            var uploadedPath = imageFile.path;
            //图片名称为上传时间+图片本名
            var imageName = moment(Date.now()).format("YYYY-MM-DD HH:mm:ss") + imageFile.originalFilename;
            var dstPath = filepath + imageName;
            //重命名为真实文件名
            fs.rename(uploadedPath, dstPath, function (err) {
                if (err) {
                    console.log('rename error: ' + err);
                } else {
                    var result = {};
                    result.code = "0";
                    result.imageUrl = filepath + imageName;
                    result.msg = "上传成功";
                    res.status(200).send(result);
                }
            });
        }
    });
}